new Vue({
    el: '#app',
    mixins: [Save],//组件配置文件，路径/utils/components.js
    data() {
        return {
            dataForm: {
                Start_Quantity: '0',
                Unit_Quantity: '0',
                Detailed_Address: '',
                Enterprise_Info_SerialNumber: ''
            },
            Trading_SerialNumber: [],//可支持付款类型
            Payment_Method_SerialNumber: [],//可支持支付方式
            Shipment_Method_SerialNumber: [],//可支持装运方式
            Transport_Method_SerialNumber: [],//可支持运输方式
            transaction: {
                Trading_SerialNumber: [],
                Payment_Method_SerialNumber: [],
                Shipment_Method_SerialNumber: [],
                Transport_Method_SerialNumber: [],
            },//交易类型 （单拎出来主要方便校验）
            // 分阶段付款相关
            stagePayments: [
                { stage: '定金', percent: 0, payTime: '', remark: '' },
                { stage: '发货', percent: 0, payTime: '', remark: '' },
                { stage: '到货', percent: 0, payTime: '', remark: '' },
                { stage: '尾款', percent: 0, payTime: '', remark: '' },
            ],
            staged_payment: [], // 子表：待提交的分阶段付款记录
            // 修改模式下：已存在子表记录映射（按阶段名），以及需要删除的重复记录
            _existingStageByName: {},
            _existingStageDuplicates: [],
            article_info: [], // 可选商品
            transport_method: [], // 运输方式
            shipment_method: [], // 装运方式
            payment_method: [], // 付款方式
            article_unit: [], // 单位
            enterprise_info: [],//企业
            city: [],
            trading: [],// 付款类型
            referrer: '', 
            fullPayStage: ''
        }
    },
    mounted() {
        /**
         * 组件配置文件中自动执行方法
         * 1.this.init(); //初始化文件
         * 2.this.getData(); //仅修改时执行，根据BOM配置属性查询
         */
        this.referrer = document.referrer;
        this.getList();
    },
    computed: {
        isStageSelected() {
            const ts = this.transaction.Trading_SerialNumber || [];
            try {
                const hasStr = Array.isArray(ts) && ts.includes('1');
                const hasObj = Array.isArray(ts) && ts.some(v => (v && v.Trading_SerialNumber) === '1');
                return hasStr || hasObj;
            } catch (e) { return false; }
        },
        isFullSelected() {
            const ts = this.transaction.Trading_SerialNumber || [];
            try {
                const hasStr = Array.isArray(ts) && ts.includes('0');
                const hasObj = Array.isArray(ts) && ts.some(v => (v && v.Trading_SerialNumber) === '0');
                return hasStr || hasObj;
            } catch (e) { return false; }
        },
        showStageTable() {
            return this.isStageSelected || this.isFullSelected;
        },
        stageTotalPercent() {
            try {
                return (this.stagePayments || []).reduce((s, i) => {
                    const n = parseFloat(String(i.percent||0).toString().replace(/[^\d.\-]/g,''));
                    return s + (isFinite(n) ? n : 0);
                }, 0);
            } catch (e) { return 0; }
        }
    },
    watch: {
        Trading_SerialNumber(val) {
            if (this.action == 'Modify') {
                this.transaction.Trading_SerialNumber = val.map(i => i.Trading_SerialNumber);
            }
        },
        Payment_Method_SerialNumber(val) {
            if (this.action == 'Modify') {
                this.transaction.Payment_Method_SerialNumber = val.map(i => i.Payment_Method_SerialNumber);
            }
        },
        Shipment_Method_SerialNumber(val) {
            if (this.action == 'Modify') {
                this.transaction.Shipment_Method_SerialNumber = val.map(i => i.Shipment_Method_SerialNumber);
            }
        },
        Transport_Method_SerialNumber(val) {
            if (this.action == 'Modify') {
                this.transaction.Transport_Method_SerialNumber = val.map(i => i.Transport_Method_SerialNumber);
            }
        }
    },
    methods: {
        phoneValidator(rule, value, callback) {
            const v = String(value || '').trim();
            if (!validatemobile(v)) {
                callback(new Error('请输入有效手机号'));
                return;
            }
            callback();
        },
        // 页面初始化完成（由混入的Save在Modify模式完成主/子表加载后调用）
        async documentLoadFinished() {
            await this.syncExistingStagedPayments();
        },
        onTradingChange(val) {
            let arr = Array.isArray(val) ? val.slice() : [val];
            if (arr.length > 1) {
                const last = arr[arr.length - 1];
                this.$message({ type: 'warning', message: '付款类型只能选择一种，已保留最新选择' });
                arr = [last];
            }
            this.transaction.Trading_SerialNumber = arr;
            this.changeChildDataForm(arr, 'Trading_SerialNumber');
            if (this.isFullSelected && !this.fullPayStage) {
                this.stagePayments = this.stagePayments.map(sp => ({ ...sp, percent: 0, payTime: '' }));
            }
        },
        handleFullStageChange() {
            const sel = this.fullPayStage;
            this.stagePayments = this.stagePayments.map(sp => {
                if (sp.stage === sel) {
                    return { ...sp, percent: 100 };
                }
                return { ...sp, percent: 0, payTime: '' };
            });
        },
        getList() { // 初始化数据
            // 查询主数据
            httpRequest({
                url: '/generalBusiness/queryMultiTableByCondition',
                data: {
                    Data: JSON.stringify([{
                        tableName: 'article_info',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'transport_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'shipment_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'payment_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'article_unit',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }])
                },
            }).then(data => {
                const { article_info, transport_method, shipment_method, payment_method, article_unit } = data;
                this.article_info = article_info;
                this.transport_method = transport_method;
                this.shipment_method = shipment_method;
                this.payment_method = payment_method;
                this.article_unit = article_unit;
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })

            httpRequest({
                url: '/generalBusiness/generalQueryBySQLSerialNumber',
                data: {
                    SQLSerialNumber: 'f_user_mapping_enterprise',
                    Condition: utf8ToBase64(getCookie('user')),
                    ExtensionCondition: ''
                }
            }).then(data => {
                this.enterprise_info = data;
                if (data.length == 1 && this.action == 'Add') {
                    this.dataForm.Enterprise_Info_SerialNumber = data[0].Enterprise_Info_SerialNumber;
                }
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })

            // 地址 
            $.ajax({
                url: absolutepath() + 'admin/data/dtree.json',
                type: 'GET',
                success: (data) => {
                    this.city = data;
                },
            })

            $.ajax({
                url: absolutepath() + 'admin/data/trading.json',
                type: 'GET',
                success: (data) => {
                    this.trading = data;
                },
            })
        },
        // 修改模式：加载并按阶段名去重已有分阶段付款记录
        async syncExistingStagedPayments() {
            try {
                if (this.action !== 'Modify') return;
                const parentId = this.nodeKey;
                if (!parentId) return;
                const rows = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'supply_unitprice_staged_payment',
                    Condition: `Supply_Unit_Price_SerialNumber='${parentId}'`
                });
                // 阶段固定顺序映射
                const orderMap = { '定金': 1, '发货': 2, '到货': 3, '尾款': 4 };
                const byStage = {};
                const duplicates = [];
                // 先按创建时间降序，保证最新的留下
                const sorted = (rows || []).slice().sort((a, b) => {
                    const ao = orderMap[a.Stage_Name] || 99;
                    const bo = orderMap[b.Stage_Name] || 99;
                    if (ao !== bo) return ao - bo;
                    const ad = new Date(a.Create_Datetime || 0).getTime();
                    const bd = new Date(b.Create_Datetime || 0).getTime();
                    return bd - ad;
                });
                for (const r of sorted) {
                    const key = String(r.Stage_Name || '');
                    if (!byStage[key]) {
                        byStage[key] = r; // 保留每个阶段的最新一条
                    } else {
                        // 其余归为重复，提交时标记删除
                        duplicates.push({ ...r, Row_Status: '1' });
                    }
                }
                this._existingStageByName = byStage;
                this._existingStageDuplicates = duplicates;
                // 将保留的记录映射到界面四阶段
                this.stagePayments = this.stagePayments.map(sp => {
                    const ex = byStage[sp.stage];
                    if (!ex) return sp;
                    return {
                        stage: sp.stage,
                        percent: Number(ex.Percent || 0),
                        payTime: String(ex.Pay_Time || ''),
                        remark: String(ex.Remark || '')
                    };
                });
            } catch (e) {
                console.error(e);
                // 加载失败不阻塞提交，只在控制台记录
            }
        },
        // 取消独立保存按钮，提交时自动构造 staged_payment
        changeCity(val) {
            this.dataForm.ProvinceNumber = val ? (val.substring(0, 2) + '0000') : '';
            this.dataForm.CityNumber = val ? (val.substring(0, 4) + '00') : '';
            this.dataForm.Detailed_Address = '';
        },
        changeChildDataForm(val, formName) { //付款方式
            this[formName] = val.map(i => {
                let obj = new Object();
                obj[formName] = i
                return obj;
            })
        },
        Input_Total_Quantity(val) {
            this.dataForm.Remain_Quantity = val;
        },
        onPercentInput(val, row) {
            const v = parseFloat(String(val || 0).toString().replace(/[^\d.\-]/g, ''));
            const safe = isFinite(v) ? v : 0;
            const others = (this.stagePayments || []).reduce((s, r) => {
                if (r === row) return s;
                const n = parseFloat(String(r.percent || 0).toString().replace(/[^\d.\-]/g, ''));
                return s + (isFinite(n) ? n : 0);
            }, 0);
            const maxAvail = Math.max(0, 100 - others);
            if (safe > maxAvail) {
                row.percent = maxAvail;
                this.$message.warning('金额比总和不能超过100%');
                return;
            }
            row.percent = safe;
        },
        handleBack() {
            window.location.href = this.referrer;
        },

        
        generateStructure() { // 生成提交结构，支持新增与修改的重新提交（统一设为待审核）
            const { tableName, formName, primaryKey } = $('#form').data('options');
            let data = [{ tableName, formName, primaryKey }];
            // 获取子表数据
            $('#form').children().each(function () {
                data.push($(this).data('options'));
            })

            // 处理子表 Children 填充企业编号
            if (data.length > 1) {
                const map = {};
                data.forEach(item => { map[item.tableName] = { ...item }; });
                data.forEach(item => {
                    const parentTableName = item.parentTableName;
                    if (parentTableName && map[parentTableName]) {
                        if (!this[map[parentTableName]['formName']].hasOwnProperty('Children')) {
                            this[map[parentTableName]['formName']].Children = new Object();
                        }
                        this[map[parentTableName]['formName']].Children[item.tableName] = this[map[item.tableName]['formName']].map(obj => {
                            return { ...obj, Enterprise_Info_SerialNumber: getCookie('enterprise') }
                        });
                    }
                });
            }

            // 统一设置企业编号与待审核状态
            this[formName]['Enterprise_Info_SerialNumber'] = getCookie('enterprise');
            this[formName]['Row_Status'] = '9'; // 待审核

            let lJSONObject_DataSet = new Object();
            if (this.action === 'Add') {
                let lJSONObject_Add = new Object();
                lJSONObject_Add[tableName] = [this[formName]];
                lJSONObject_DataSet = { Add: lJSONObject_Add };
                const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0', Operation_Path: getRelativePath(),
                    Operation_Description: '发布供应提交（待审核）', Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody", Operation_IP: getIpAddress()
                }]
            } else { // Modify 编辑重新提交
                const { add, modify } = this.deal(this[formName]);
                let lJSONObject_Modify = new Object();
                lJSONObject_Modify[tableName] = [modify];

                lJSONObject_DataSet = { Modify: lJSONObject_Modify, Add: {} };
                if (add != null) {
                    lJSONObject_DataSet.Add[tableName] = [add];
                }
                const Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0', Operation_Path: getRelativePath(),
                    Operation_Description: `供应重新提交（待审核）${this._resubmitReason ? '，原因：' + this._resubmitReason : ''}`,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody", Operation_IP: getIpAddress()
                }]
            }
            return lJSONObject_DataSet;
        },
        async handleSubmit() { // 点击提交（新增或编辑重新提交）
            const allValid = await this.validateAllForms();
            if (!allValid) {
                this.$message({ message: '存在未填写的必填项！', type: 'warning' });
                return;
            }
            // 选择了阶段付款：校验比例并构造子表数据
            if (this.isStageSelected) {
                const total = this.stageTotalPercent;
                if (total !== 100) {
                    this.$message.warning(`分阶段付款比例总和为 ${total}%，请调整为 100%`);
                    return;
                }
                // 校验付款天数为非负整数
                for (const r of (this.stagePayments || [])) {
                    const s = String(r.payTime || '').trim();
                    if (s === '') {
                        this.$message.warning('请填写每个阶段的付款天数');
                        return;
                    }
                    if (!/^\d+$/.test(s)) {
                        this.$message.warning('付款天数需为非负整数，例如：7');
                        return;
                    }
                }
                // 构造提交：已有阶段→修改（带*_Original），多余重复→删除，缺失→新增
                const byStage = this._existingStageByName || {};
                const addsOrModifies = (this.stagePayments || []).map(sp => {
                    const ex = byStage[sp.stage];
                    const base = {
                        Stage_Name: String(sp.stage || ''),
                        Percent: String(sp.percent || 0),
                        Pay_Time: String(sp.payTime || ''),
                        Remark: String(sp.remark || ''),
                        Row_Status: '0'
                    };
                    if (ex) {
                        // 拷贝所有 *_Original 字段用于修改识别
                        Object.keys(ex).forEach(k => {
                            if (/_Original$/.test(k)) base[k] = ex[k];
                        });
                    }
                    return base;
                });
                const deletes = (this._existingStageDuplicates || []).map(ex => {
                    const obj = { Row_Status: '1' };
                    // 保留所有原值字段用于定位删除对象
                    Object.keys(ex).forEach(k => { obj[k] = ex[k]; });
                    return obj;
                });
                this.staged_payment = [...addsOrModifies, ...deletes];
            } else if (this.isFullSelected) {
                // 全额付款：仅允许一个阶段，比例自动 100，其他阶段不提交或删除旧有记录
                if (!this.fullPayStage) {
                    this.$message.warning('请选择一个阶段作为全额付款节点');
                    return;
                }
                const sel = (this.stagePayments || []).find(sp => sp.stage === this.fullPayStage) || { stage: this.fullPayStage, percent: 100, payTime: '', remark: '' };
                const s = String(sel.payTime || '').trim();
                if (s === '') {
                    this.$message.warning('请填写所选阶段的付款天数');
                    return;
                }
                if (!/^\d+$/.test(s)) {
                    this.$message.warning('付款天数需为非负整数，例如：7');
                    return;
                }
                const byStage = this._existingStageByName || {};
                const ex = byStage[sel.stage];
                const base = {
                    Stage_Name: String(sel.stage || ''),
                    Percent: '100',
                    Pay_Time: String(sel.payTime || ''),
                    Remark: String(sel.remark || ''),
                    Row_Status: '0'
                };
                if (ex) {
                    Object.keys(ex).forEach(k => { if (/_Original$/.test(k)) base[k] = ex[k]; });
                }
                // 删除重复记录 + 删除非所选阶段的既有记录
                const deletesDup = (this._existingStageDuplicates || []).map(d => { const o = { Row_Status: '1' }; Object.keys(d).forEach(k => o[k] = d[k]); return o; });
                const deletesOthers = Object.keys(byStage).filter(name => name !== sel.stage).map(name => {
                    const row = byStage[name]; const obj = { Row_Status: '1' }; Object.keys(row).forEach(k => obj[k] = row[k]); return obj;
                });
                this.staged_payment = [base, ...deletesDup, ...deletesOthers];
            } else {
                this.staged_payment = [];
            }
            this.loading = true;
            try {
                const lJSONObject_DataSet = this.generateStructure();
                const res = await generalApi.generalSaveByRequestBody({ Data: lJSONObject_DataSet });
                if (res.Status == "success") {
                    this.$message.success("提交成功，待审核");
                    window.location.href = './index.html';
                } else {
                    this.$message.error("提交失败，请重试！");
                }
            } catch (error) {
                console.error(error);
                this.$message.error("系统错误，请联系开发者!")
            } finally {
                this.loading = false;
            }
        }
    }
})
